package main

import (
	//"fmt"
	"net"
	"strings"
)
type User struct{
	Name string
	Addr string
	C chan string
	Conn net.Conn

	Server *Server//user类型里面新增server关联
}
//创建一个User的api
func NewUser(conn net.Conn,server *Server) *User{
	userAddr := conn.RemoteAddr().String()
	user := &User{
		Name:userAddr,
		Addr:userAddr,
		C: make(chan string),
		Conn:conn,
		Server:server,//user类型里面新增server关联
	}
	go user.ListenMessage()
	return user
}
//用户上线
func (this *User)Online(){
	//用户上线，将用户加入到onlinemap当中
	this.Server.mapLock.Lock()
	this.Server.OnlineMap[this.Name]=this
	this.Server.mapLock.Unlock()

	//广播当前用户上线消息
	this.Server.BroadCast(this,"我已上线")
}
//用户下线
func (this *User)Offline(){
	//用户下线，将用户从onlinemap当中删掉
	this.Server.mapLock.Lock()
	delete(this.Server.OnlineMap,this.Name)
	//this.Server.OnlineMap[this.Name]=this
	this.Server.mapLock.Unlock()

	//广播当前用户上线消息
	this.Server.BroadCast(this,"我已下线")
}
//给当前User对应的客户端发送消息
func (this *User)SendMsg(msg string){
	this.Conn.Write([]byte(msg))
}
//用户处理消息的业务
func (this *User)Domessage(msg string){
	if msg == "who"{
		//查询当前在线用户都有哪些
		this.Server.mapLock.Lock()
		for _,user := range this.Server.OnlineMap{
			OnlineMsg := "["+user.Addr+"]"+user.Name+":"+"在线...\n"
			this.SendMsg(OnlineMsg)
		}
		this.Server.mapLock.Unlock()
	}else if len(msg) > 7 && msg[:7] == "rename|"{
		//消息格式:rename|张三
		newName := string(msg[7:])
		//fmt.Println(newName)
		_,ok := this.Server.OnlineMap[newName]
		if ok{
			this.SendMsg("该用户名已被使用")
		}else{
			this.Server.mapLock.Lock()
			delete(this.Server.OnlineMap,this.Name)
			this.Server.OnlineMap[newName]=this
			this.Server.mapLock.Unlock()
			this.Name=newName
			this.SendMsg("你已经更新用户名为："+this.Name+"\n")
		}
		
	}else if len(msg)>4 && msg[:3]=="to|"{
		//消息格式 : to|张三|消息内容
		//获取对方的用户名
		remoteName := strings.Split(msg,"|")[1]
		if remoteName == ""{
			this.SendMsg("消息格式不正确，请使用\"to|张三|你好呀\"格式。\n")
			return
		}
		remoteUser,ok := this.Server.OnlineMap[remoteName]
		if !ok{
			this.SendMsg("该用户不存在\n")
			return
		}
		content := strings.Split(msg,"|")[2]
		if content == ""{
			this.SendMsg("无消息内容，请重发\n")
			return
		}
		remoteUser.SendMsg(this.Name+"对你说:"+content)
	}else{
		this.Server.BroadCast(this,msg)
	} 
}
//监听当前的User channel的方法，一旦有消息，就直接发送给对端客户端
func (this *User)ListenMessage(){
	for{
		msg := <-this.C
		this.Conn.Write([]byte(msg+"\n"))
	}
}